<template>
	<view class="edit-profile">
		<view class="headnavi">
			<image class="arrow" src="../../static/home/main/details/arrow.png" @click="goBack()"></image>
			<view class="navi-title">编辑资料</view>
		</view>
		<view class="changeAvatar" @click="uploAdvatar">
			<image :src="avatarSrc" class="avatar"></image>
			<text class="body-normal-text">修改头像</text>
			<!-- <image class="arrow" src="../../static/tabbar_new/路径 1.png"></image> -->
		</view>
		<view class="changeUsername" @click="edit">
			<text class="body-normal-text">用户名</text>
			<view class="changeContainer">
				<text class="username">{{userInfo.userName}}</text>
				<image class="arrow" src="../../static/tabbar_new/arrow.png"></image>
			</view>

		</view>

		<div class="edit">
			<!-- 灰色遮罩 -->
			<div class="overlay" v-if="showModal" @click="closeModal"></div>
			<!-- 弹窗内容 -->
			<div class="modal" v-if="showModal">
				<h2 style="text-align: center;">编辑用户名</h2>
				<textarea v-model="userNameText"
					style="background-color: #E5E5E5;width: 100%;margin: 2vh 0;padding: 10px;box-sizing: border-box;"></textarea>
				<button @click="editSubmit">提交</button>
			</div>
		</div>

		<uni-popup ref="message" type="message" class="login-message" style="z-index: 1001;">
			<uni-popup-message :type="msgType" :message="messageText" :duration="1000" border-radius="100px"
				class="login-message"></uni-popup-message>
		</uni-popup>

	</view>

</template>

<script>
	export default {
		data() {
			return {
				avatarSrc: '/static/chishenme/morentouxiang.jpg',
				showModal: false, // 控制弹窗显示/隐藏
				msgType: 'success',
				messageText: '这是一条成功提示',
				imgID:"",
				userInfo: {
					userName: '',
					userImg: '',
					id: '',
					
					/* followersCount: 0, //关注的人
					fansCount: 0, //粉丝数 */
				},
				userNameText: '',
			}
		},
		mounted() {
			const userInfo = uni.getStorageSync('userInfo');
			this.userInfo.userName = userInfo.data.userName;
			this.userInfo.id = userInfo.data.id;
		},
		onShow(){
			const userInfo = uni.getStorageSync('userInfo');
			this.getAvatar(userInfo.data.avatar);
			/* this.getAvatar(this.userInfo.userImg) */
		},
		methods: {
			getUserDetail(){
				const userInfo = uni.getStorageSync('userInfo');
				const url='http://localhost:8080/user/detail/'+userInfo.data.id;
				uni.request({
					url:url,
					method:'GET',
					success:res=>{
						uni.setStorageSync('userInfo',res.data);
						const userInfo = uni.getStorageSync('userInfo');
						
						this.popMessage("success", "头像更改成功！");
						setTimeout(() => {
							uni.reLaunch({
							  url: '/pages/editProfile/editProfile' // 当前页面的路径
							});
						}, 1000);
					},
					fail: (err) => {
						this.popMessage("error", "头像更改失败");
						console.error(err);
						// 在这里处理请求失败的逻辑
					}
				});
			},
			getAvatar(id11){
				uni.request({          //获取图片
					url: 'http://localhost:8080/image/getImage?id='+id11,
					method: 'GET',
					success: res1 => {
							// console.log("根据文件地址获得的base64编码图片"); 
							// console.log(res1.data.data.data)
							// // 将base64字符串转换为ArrayBuffer格式
							// const arrayBuffer = uni.base64ToArrayBuffer(res1.data.data.data);
							// // 将ArrayBuffer转换为Blob对象
							// const blob = new Blob([arrayBuffer], { type: 'image/png' });
							// // 创建Blob URL
							// const imgUrl = URL.createObjectURL(blob);
							const base64Data = res1.data.data.data;
							// 直接设置图片 src 属性
							const imgUrl = `data:image/png;base64,${base64Data}`;
							
							this.avatarSrc=imgUrl;
							// this.button1img = imgUrl;
							
							
							
					},
					fail: (err) => {
						console.error(err);
						// 在这里处理请求失败的逻辑
					}
				});
			},
			uploadFile(file){
				uni.showLoading({title: '上传中', mask:true});
				uni.uploadFile({
					url: 'http://localhost:8080/image/upload', // 服务器的地址，确保与实际部署的地址相符
					filePath: file,
					name: 'file', // 服务器端接收文件的字段名，与multer中间件配置的一致
					success: res => {
							console.log("上传后获得的文件地址"); 
							// console.log(res.data); 
							const jsonString = res.data;
							const jsonObject = JSON.parse(jsonString);
							const id11 = jsonObject.data;
							const userInfo = uni.getStorageSync('userInfo');
							console.log("id11")
							console.log(id11)
							const formData = {
								// userName: userInfo.data.userName
								// password: userInfo.data.password,
								avatar:id11,
								id:userInfo.data.id
							};
							const url= 'http://localhost:8080/user/edit';
							uni.request({
								url:url,
								method:'PUT',
								data: formData,
								success:res=>{
									this.getUserDetail();
								},
								fail: (err) => {
									console.error(err);
									// 在这里处理请求失败的逻辑
								}
							});
						    this.imgID=id11;
							uni.hideLoading();
							
					},
					fail: err => {
					    console.log(err);
						uni.hideLoading();
						uni.showToast({
								title: '上传失败',//显示的文字
						        duration: 1000,  //显示多少时间，默认1500毫秒
						        icon: "error"  ,//自定义显示的图标，默认成功success，错误error,加载loading，不显示图标是none
								mask:true,
						})
					}
				});
			
			},
			uploAdvatar(){
				
				uni.chooseImage({
				  count: 1,
				  success: res => {
				    const tempFilePaths = res.tempFilePaths;
				    this.userInfo.userImg = tempFilePaths[0];
				    this.uploadFile(tempFilePaths[0]);
				  },
				  fail: err => {
				    console.log(err);
				    uni.hideLoading();
				  },
				});
			},
			goBack() {
				uni.navigateTo({
					url: '/pages/config/config'
				})
			},
			flush() {
				uni.navigateTo({
					url: getCurrentPages()[getCurrentPages().length - 1].route // 获取当前页面的路由并导航到它  
				});
				uni.navigateBack({
					delta: 1
				}); // 随后返回一页以去除多余的页面
			},

			edit() {
				this.showModal = true;
			},
			closeModal() {
				this.showModal = false; // 关闭弹窗
			},
			editSubmit() {
				const formData = {
					id: this.userInfo.id,
					userName: this.userNameText,
					/* avatar:this.imgID, */
				};

				uni.showLoading({

				})

				uni.request({
						url: 'http://localhost:8080/user/edit',
						method: 'PUT',
						data: formData,
					})
					.then(response => {
						console.log(response);
						uni.setStorageSync('userInfo', response[1].data);
						this.popMessage("success", "编辑成功！");
						setTimeout(() => {
							uni.reLaunch({
							  url: '/pages/editProfile/editProfile' // 当前页面的路径
							});
						}, 1000);
					})
					.catch(error => {
						console.error(error);
						this.popMessage("error", "编辑失败");
					})
					.finally(() => {
						uni.hideLoading();
					});
			},
			popMessage(type, text) {
				this.msgType = type
				this.messageText = text
				this.$refs.message.open()
			},
		}
	}
</script>

<style lang="scss">
	.edit-profile {
		display: flex;
		flex-direction: column;

		.body-normal-text {
			font-size: 35rpx;
			color: #303133;

		}



		.headnavi {
			/* height: 10%; */
			width: 100vw;
			background-color: white;
			position: sticky;
			display: flex;

			box-shadow: 0rpx 10rpx 20rpx 0rpx #e5e5e5;
			padding-bottom: 1vh;

			.arrow {
				/* transform: rotate(180deg); */
				width: 6vw;
				height: 3vh;
				margin-top: 5vh;
				margin-left: 5vw;
			}

			.navi-title {
				margin-top: 5vh;
				margin-left: 29vw;
				font-size: 40rpx;
				color: #FF8D1A;

			}
		}

		.changeAvatar {
			display: flex;
			padding: 17rpx 35rpx 17rpx 35rpx;
			border-bottom: 2px solid #e5e5e5;
			flex-direction: column;

			.avatar {
				border-radius: 20vw;
				width: 20vw;
				height: 20vw;
				/* margin-right: 35rpx; */
				align-self: center;
			}

			.body-normal-text {
				align-self: center;
				font-size: 28rpx;
				padding: 5rpx 10rpx 5rpx 10rpx;
				margin-top: 17rpx;
				background-color: #FF8D1A;
				border-radius: 40rpx;
				/* padding-left: 35rpx; */
				/* margin-left: auto; */
			}

		}

		.changeUsername {
			display: flex;
			padding: 17rpx 35rpx 17rpx 35rpx;
			border-bottom: 2px solid #e5e5e5;

			/* flex-direction: column; */
			/* .avatar {
				border-radius: 20vw;
				width: 20vw;
				height: 20vw;
				/* margin-right: 35rpx; */
			/* align-self: center;
			} */
			.body-normal-text {
				align-self: center;
				/* padding-left: 35rpx; */
				/* margin-left: auto; */
			}

			.changeContainer {
				align-self: center;
				display: flex;
				margin-left: auto;

				.arrow {
					height: 5vw;
					width: 5vw;
				}

				.username {
					font-size: 35rpx;
					color: #717378;
					font-weight: bold;
				}
			}

		}

		.edit {
			.overlay {
				position: fixed;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-color: rgba(0, 0, 0, 0.5);
				/* 半透明黑色背景 */
				z-index: 999;
				/* 确保遮罩层在弹窗上方 */
			}

			.modal {
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				background-color: white;
				padding: 10px;
				z-index: 1000;
				/* 确保弹窗在遮罩层上方 */
				border-radius: 30px 30px 0 0;
			}
		}
	}
</style>